package com.adk.backend.controller;

import com.adk.backend.common.PageResult;
import com.adk.backend.common.Result;
import com.adk.backend.entity.LxBillingList;
import com.adk.backend.service.FinanceService;
import com.adk.backend.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 财务管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/finance")
public class FinanceController {
    
    @Autowired
    private FinanceService financeService;
    
    @Autowired
    private LogUtil logUtil;
    
    /**
     * 分页查询账单列表
     */
    @GetMapping("/bill/list")
    public Result<PageResult<Map<String, Object>>> getBillList(
            @RequestParam(required = false) Long customerId,
            @RequestParam(required = false) Integer shipType,
            @RequestParam(required = false) Integer paid,
            @RequestParam(required = false) Integer isBill,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        
        Map<String, Object> params = new HashMap<>();
        params.put("customerId", customerId);
        params.put("shipType", shipType);
        params.put("paid", paid);
        params.put("isBill", isBill);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        
        PageResult<Map<String, Object>> result = financeService.getBillList(params);
        return Result.success(result);
    }
    
    /**
     * 根据订单ID查询账单
     */
    @GetMapping("/bill/detail")
    public Result<LxBillingList> getBillDetail(@RequestParam Long orderId, @RequestParam Integer shipType) {
        LxBillingList bill = financeService.getBillByOrderId(orderId, shipType);
        if (bill != null) {
            return Result.success(bill);
        }
        return Result.error("账单不存在");
    }
    
    /**
     * 创建账单
     */
    @PostMapping("/bill/create")
    public Result<LxBillingList> createBill(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        try {
            Long userId = (Long) httpRequest.getAttribute("userId");
            
            LxBillingList bill = new LxBillingList();
            bill.setOrderId(Long.valueOf(request.get("orderId").toString()));
            bill.setShipType((Integer) request.get("shipType"));
            bill.setCurrencyId((Integer) request.getOrDefault("currencyId", 1));
            bill.setExchangeRateSar((BigDecimal) request.getOrDefault("exchangeRateSar", BigDecimal.ONE));
            bill.setExchangeRateUsd((BigDecimal) request.getOrDefault("exchangeRateUsd", BigDecimal.ONE));
            
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> details = (List<Map<String, Object>>) request.get("details");
            
            LxBillingList result = financeService.createBill(bill, details, userId != null ? userId.intValue() : null);
            
            // 记录操作日志（与PHP逻辑一致：action_logs($_SESSION['userid'], "billing_list", $billing_id, "创建账单");）
            if (userId != null && result.getId() != null) {
                logUtil.logAction(userId, "billing_list", result.getId(), "创建账单");
                logUtil.logAction(userId, "order_list", bill.getOrderId(), "创建账单");
            }
            
            return Result.success("Success.", result);
        } catch (Exception e) {
            log.error("创建账单失败", e);
            return Result.error("Data Error");
        }
    }
    
    /**
     * 更新付款状态
     */
    @PostMapping("/bill/pay")
    public Result<Boolean> updatePayStatus(
            @RequestParam Long billId,
            @RequestParam Integer paid,
            @RequestParam(required = false) BigDecimal paidAmount,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            boolean result = financeService.updatePayStatus(billId, paid, paidAmount, userId != null ? userId.intValue() : null);
            if (result) {
                // 记录操作日志（与PHP逻辑一致）
                if (userId != null) {
                    // PHP中更新付款状态没有单独记录日志，这里也不记录
                }
                return Result.success("Success.", true);
            }
            return Result.error("Data Error");
        } catch (Exception e) {
            log.error("更新付款状态失败", e);
            return Result.error("Data Error");
        }
    }
    
    /**
     * 获取账单明细
     */
    @GetMapping("/bill/details")
    public Result<List<Map<String, Object>>> getBillDetails(@RequestParam Long billId) {
        try {
            List<Map<String, Object>> details = financeService.getBillDetails(billId);
            return Result.success(details);
        } catch (Exception e) {
            log.error("获取账单明细失败", e);
            return Result.error("获取账单明细失败");
        }
    }
}

